package org.sq;

import java.io.File;
import java.util.HashMap;


import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import ar.com.daidalos.afiledialog.FileChooserDialog;
import ar.com.daidalos.afiledialog.FileChooserDialog.OnFileSelectedListener;

public class WelcomeActivity extends Activity {
	protected static final int HANDLE_ERROR = 99;
	private static final int REQUEST_CHOOSER = 1234;
	TextView fileErrorView;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.welcome);
		fileErrorView = (TextView) findViewById(R.id.file_error);

	}

	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
	}
	
	public void downloadAction(View v){
		Intent browserIntent = new Intent(Intent.ACTION_VIEW,
				Uri.parse("http://www.sq.dp.ua/files/android/"));
		startActivity(browserIntent);
	}
	
	public void pickerAction(View v){
		//Intent intent = new Intent(this, FileChooserActivity.class);
		//Intent getContentIntent = FileUtils.createGetContentIntent(
		 //Intent intent = Intent.createChooser(getContentIntent, "Select a file");
		// startActivityForResult(intent, REQUEST_CHOOSER);
		FileChooserDialog dialog = new FileChooserDialog(this);
		dialog.loadFolder(Environment.getExternalStorageDirectory() + "/Download/");
		//dialog.setTitle("Выберите файл");
		dialog.setFilter(".*sq|.*SQ");
		dialog.addListener(new OnFileSelectedListener(){

			@Override
			public void onFileSelected(Dialog source, File file) {
				// TODO Auto-generated method stub
				source.hide();
				Toast.makeText(WelcomeActivity.this, file.getPath(), Toast.LENGTH_LONG).show();
				final LevelManager levelManager = ((SQApp) getApplicationContext()).levelManager();
				levelManager.setQuestFilePath(file.getPath());
				startNewGame();
			}

			@Override
			public void onFileSelected(Dialog source, File folder, String name) {
				// TODO Auto-generated method stub
				
			}
			
		});
		 dialog.show();
	}

	public void openSq(View v) {
		Intent browserIntent = new Intent(Intent.ACTION_VIEW,
				Uri.parse("http://www.sq.dp.ua"));
		startActivity(browserIntent);

	}

	public void onStart() {
		super.onStart();
		final LevelManager levelManager = ((SQApp) getApplicationContext()).levelManager();
		if (levelManager.hasSaveGameFile()) {
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setCancelable(false);
			builder.setTitle(getString(R.string.info));
			builder.setMessage(getString(R.string.saved_game_prompt));
			builder.setPositiveButton(getString(R.string.saved_game),
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							loadGame();
						}
					});
			builder.setNegativeButton(getString(R.string.new_game),
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							//startNewGame();
						}
					});

			AlertDialog alert = builder.create();
			alert.show();
		} else {
			//startNewGame();
		}
	}

	void startNewGame() {
		final LevelManager levelManager = ((SQApp) getApplicationContext()).levelManager();
		
		new Thread() {
			public void run() {
				if (levelManager.hasNewGameFile()) {
					showSmallActivityIndicatorHandler.sendEmptyMessage(0);
					clearDataDir();
					clearExtDataDir();
					try {
						levelManager.copyNewGame();
						levelManager.readNextLevel();
						hideSmallActivityIndicatorHandler.sendEmptyMessage(0);
						updateOverlayHandler.sendEmptyMessage(0);

					} catch (Exception e) {
						hideSmallActivityIndicatorHandler.sendEmptyMessage(0);
						updateOverlayHandler.sendEmptyMessage(HANDLE_ERROR);
						Log.e("Error", "" + e.getLocalizedMessage());

					}

				} else {
					showFileErrorViewHandler.sendEmptyMessage(0);
				}
			}
		}.start();
		
	}

	public void emptyAction(View v) {

	}

	Handler updateOverlayHandler = new Handler() {
		public void handleMessage(Message msg) {
			if (msg.what == HANDLE_ERROR) {
				AlertDialog.Builder builder = new AlertDialog.Builder(
						WelcomeActivity.this);
				builder.setCancelable(true);
				builder.setTitle(getString(R.string.error));
				builder.setMessage(getString(R.string.file_format_error));
				builder.setPositiveButton(getString(android.R.string.ok),
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								finish();

							}
						});

				AlertDialog alert = builder.create();
				alert.show();
			} else {
				Intent intent = new Intent(WelcomeActivity.this,
						TabsActivity.class);
				startActivity(intent);
			}
		}
	};

	Handler showSmallActivityIndicatorHandler = new Handler() {
		public void handleMessage(Message msg) {
			findViewById(R.id.waitView).setVisibility(View.VISIBLE);
		}
	};

	Handler showFileErrorViewHandler = new Handler() {
		public void handleMessage(Message msg) {
			fileErrorView.setVisibility(View.VISIBLE);
		}
	};

	Handler hideSmallActivityIndicatorHandler = new Handler() {
		public void handleMessage(Message msg) {
			findViewById(R.id.waitView).setVisibility(View.INVISIBLE);
		}
	};

	void loadGame() {
		final LevelManager levelManager = ((SQApp) getApplicationContext()).levelManager();
		try {
			levelManager.restoreQuests();
			if (!levelManager.readNextLevel()) {
				if (!levelManager.readFirstLevel()) {
					return;
				}
			}

			Intent intent = new Intent(this, TabsActivity.class);
			startActivity(intent);
		} catch (Exception e) {
			Log.e("Error", "" + e.getLocalizedMessage());
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setCancelable(true);
			builder.setTitle(getString(R.string.error));
			builder.setMessage(getString(R.string.file_format_error));
			builder.setPositiveButton(getString(android.R.string.ok),
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							finish();

						}
					});

			AlertDialog alert = builder.create();
			alert.show();
		}
	}

	void clearDataDir() {
		File dataDir = this.getFilesDir();
		File[] files = dataDir.listFiles();
		for (File f : files) {
			if (f.isDirectory()) {
				DeleteRecursive(f);
			} else {
				f.delete();
			}

		}
		// Log.d("LevelManager", "After internal cleanup ");
		// String[] files1 = getFilesDir().list();
		// for (String f : files1) {
		// Log.d("LevelManager", "Find file: " + f);
		// }
	}

	void clearExtDataDir() {
		File dataDir = this.getExternalFilesDir(null);
		File[] files = dataDir.listFiles();
		for (File f : files) {
			if (f.isDirectory()) {
				DeleteRecursive(f);
			} else {
				f.delete();
			}

		}
	}

	void DeleteRecursive(File fileOrDirectory) {
		if (fileOrDirectory.isDirectory())
			for (File child : fileOrDirectory.listFiles())
				DeleteRecursive(child);
		fileOrDirectory.delete();
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
	    switch (requestCode) {
	        case REQUEST_CHOOSER:
	        if (resultCode == RESULT_OK) {
	            // Get the Uri of the selected file 
	            //Uri uri = data.getData();
	            //Log.d("SQ", "File Uri: " + uri.toString());
	            // Get the path
	            //String path = FileUtils.getPath(this, uri);
	            //WelcomeActivity.Log.d("SQ", "File Path: " + path);
	            // Get the file instance
	            // File file = new File(path);
	            // Initiate the upload
	        }
	        break;
	    }
	    super.onActivityResult(requestCode, resultCode, data);
	}
}
